package com.marmot.cloud.framework.orm.jpa.service.impl;

import com.marmot.cloud.framework.core.pager.PageHelper;
import com.marmot.cloud.framework.orm.jpa.service.BaseJpaCrudService;
import com.marmot.cloud.framework.core.response.PageData;
import com.marmot.cloud.framework.orm.jpa.entity.BaseJpaEntity;
import com.marmot.cloud.framework.orm.jpa.repository.BaseJpaCrudRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Optional;


public class BaseJpaCrudServiceImpl<M extends BaseJpaCrudRepository<T, ID>, T extends BaseJpaEntity, ID> implements BaseJpaCrudService<M, T, ID> {

    @Autowired
    M baseCrudRepository;

    @Override
    public T save(T t) {
        return baseCrudRepository.save(t);
    }

    @Override
    public void saveAll(List<T> list) {
        baseCrudRepository.saveAll(list);
    }

    @Override
    public T update(T t) {
        return baseCrudRepository.saveAndFlush(t);
    }

    @Override
    public void updateAll(List<T> list) {
        list.forEach(vo -> {
                    update(vo);
                }
        );
    }

    @Override
    public void delete(ID id) {
        baseCrudRepository.deleteById(id);
    }

    @Override
    public void deleteAll(List<T> list) {
        baseCrudRepository.deleteAll(list);
    }

    @Override
    public Optional<T> findById(ID id) {
        return baseCrudRepository.findById(id);
    }

    @Override
    public Page<T> findExample(T t, Pageable pageable) {
        // 设置模糊匹配 构建对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // 执行查询
        return baseCrudRepository.findAll(Example.of(t, matcher), pageable);
    }

    @Override
    public PageData<T> findExample(PageHelper<T> pageHelper) {
        // 设置字符串模糊匹配 构建对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // 执行查询
        Page<T> pagers = baseCrudRepository.findAll(Example.of(pageHelper.getQuery(), matcher), pageHelper.builder());
        // 包装返回
        return PageData.of(pagers);
    }

    @Override
    public boolean existsById(ID id) {
        return baseCrudRepository.existsById(id);
    }

}
